import copy
import random
import time
from Env import Env


class SuperEnv (Env):

    def pretend_step(self, action):

        copy_instance = copy.deepcopy(self.pocketCube)
        copy_instance.rotate_action(action)
        return copy_instance.chaosLevel

    def get_now_chaos(self):
        return self.pocketCube.chaosLevel


def main():
    env = SuperEnv()
    obs = env.state
    done = False
    step_num = 1

    lowest_chaos = 1

    start_time = time.time()

    while not done:

        # action = env.action_space.sample()
        # next_obs, reward, done, chaos = env.step(action)
        chaos_levels = []
        for action in range(12):
            chaos_levels.append(env.pretend_step(action))

        chaos_level_sorted = sorted(chaos_levels)
        threshold = chaos_level_sorted[int(len(chaos_level_sorted) * 0.5)]
        action = random.choice([index for index, i in enumerate(chaos_levels) if i <= threshold])

        next_obs, reward, done, chaos = env.step(action)
        # print(f"step#:{step_num} action:{action: >} reward:{reward:>10.3f} done:{done} chaos:{chaos}")

        step_num += 1

        if chaos < lowest_chaos:
            lowest_chaos = chaos
            print(f"step#:{step_num} reward:{reward:>10.3f} done:{done} chaos:{chaos}")

    end_time = time.time()
    time_use = end_time - start_time
    minute, sec = divmod(time_use, 60)
    print(f"\n用时 {int(minute)}分{int(sec): >2}秒")


def split_env(root_env, split_num=10):
    return [copy.deepcopy(root_env) for _ in range(split_num)]


def get_min_env(split_envs: list[SuperEnv], start_chaos: float, step: int=100):
    root_env = copy.deepcopy(split_envs[0])
    done = False
    min_chaos = start_chaos
    for _ in range(step):
        for env in split_envs:
            action = random.randint(0, 11)
            next_obs, reward, done, chaos = env.step(action)


            if chaos < min_chaos:
                min_chaos = chaos
                root_env = copy.deepcopy(env)


    print(f"start:{start_chaos} end:{root_env.get_now_chaos()}")
    return root_env, done


# 局部最优 并非 全局最优
if __name__ == '__main__':

    root_env = SuperEnv()

    done = False

    start_time = time.time()

    while not done:
        split_envs = split_env(root_env)
        now_chaos = root_env.get_now_chaos()
        root_env, done = get_min_env(split_envs, now_chaos)

        root_env.pocketCube.printState()

    end_time = time.time()
    time_use = end_time - start_time
    minute, sec = divmod(time_use, 60)
    print(f"\n用时 {int(minute)}分{int(sec): >2}秒")
